package com.yq.dataStructures.tree.huffmantree;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @ClassName HuffmanTree
 * @Description 最优二叉树，赫夫曼树
 * @Author yaoqiang
 * @Date 2021/11/17 10:24
 * @Version 1.0
 */
public class HuffmanTree {
    public static void main(String[] args) {
        int arr[] = {7, 5, 2, 4};
        //{13, 7, 8, 3, 29, 6, 1};
        Node root = createHuffmanTree(arr);
        preOrder(root);//18,7,11,5,6,2,4
    }

    /**
     * 创建huffmantree
     *
     * @param arr 需要创建成huffman的数组
     * @return 创建好huffmanTree的root节点
     */
    private static Node createHuffmanTree(int[] arr) {
        //遍历arr数组，2将arr的每个元素构成一个node 3、将node放入到arraylist
        ArrayList<Node> nodes = new ArrayList<>();
        for (int value : arr) {
            nodes.add(new Node(value));
        }
        while (nodes.size() > 1) {
            Collections.sort(nodes);
            //取出根节点最小的两颗二叉树，
            Node left = nodes.get(0);
            Node right = nodes.get(1);
            //构建父节点
            Node parent = new Node(left.value + right.value);
            parent.left = left;
            parent.right = right;
            //arraylist删除处理二叉树
            nodes.remove(left);
            nodes.remove(right);
            nodes.add(parent);
        }
        //返回root节点
        return nodes.get(0);
    }

    /**
     * 前序遍历tree
     *
     * @param root
     */
    public static void preOrder(Node root) {
        if (root != null) {
            root.preOrder();
        } else {
            System.out.println("null tree");
        }
    }

}


class Node implements Comparable<Node> {
    //节点的权值，指向左子节点和右子节点
    int value;
    Node left;
    Node right;

    //前序遍历一下
    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }

    public Node(int value) {
        this.value = value;
    }


    @Override
    public int compareTo(Node o) {
        return this.value - o.value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }
}